import { login, logout, getInfo as _getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { asyncRoutes ,constantRoutes }  from '@/router/index'
import {creatrouter, render} from '@/utils/index'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: 'admin',
    avatar: '',
    roles:[],
    routes:[] ,
 
    menu:[
      // {
      //   path: '/order',
      //   // component: Layout,
      //   meta: { title: '订单', icon: 'el-icon-user' },
      //   children: [
      //     {
      //       path: '/orderlist',
      //       meta: { title: '订单', icon: 'el-icon-user' },
      //       component:() => import('@/views/order/orderlist'),
      //     },
      //     {
      //       path: '/ordersettlement',
      //       meta: { title: '结算中心', icon: 'el-icon-user' },
      //       component:() => import('@/views/order/center'),
      //     },
      //   ]
      // },
    
    
    
      // {
      //   path: '/novel',
      //   // component: Layout,
      //   meta: { title: '小说', icon: 'form' },
      //   children: [
      //     {
      //       path: '/add',
      //       name: 'add',
      //       component: () => import('@/views/noval/add'),
      //       meta: { title: '添加小说', icon: 'form' }
      //     },
      //     {
      //       path: '/getnovel',
      //       name: 'getnovel',
      //       component: () => import('@/views/noval/getnovel'),
      //       meta: { title: '小说列表', icon: 'form' }
      //     }
      //   ]
      // },
    
    
    
    
      // {
      //   path: '/agent',
      //   // component: Layout,
      //   meta: { title: '代理', icon: 'el-icon-user' },
      //   children: [
      //     {
      //       path: 'add',
      //       meta: { title: '添加代理', icon: 'el-icon-user' },
      //       component:() => import('@/views/agent/add.vue'),
      //     },
      //     {
      //       path: '/agentlist',
      //       meta: { title: '代理', icon: 'el-icon-user' },
        
      //       component:() => import('@/views/agent/agentlist.vue'),
      //     }
      //   ]
      // },
      // {
      //   path: '/userinfo',
      //   // component: Layout,
      //   meta: { title: '客户信息', icon: 'el-icon-user' },
      //   children: [
      //     {
      //       path: '/userinfolist',
      //       meta: { title: '用户', icon: 'el-icon-user' },
      //       component:() => import('@/views/user/user'),
      //     },
      //     {
      //       path: '/userinfolist2',
      //       meta: { title: '账单地址', icon: 'el-icon-user' },
      //       component:() => import('@/views/user/user'),
      //     }
      //   ]
      // },
      //   // 404 page must be placed at the end !!!
      //   { path: '*', redirect: '/404', hidden: true }
    
    ]
    //  添加路由 都由这个routes
  }
}

const state = getDefaultState()






const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_roles: (state, roles) => {
    state.roles = roles
  },
  SET_routes:(state, data)=>{
    state.routes = data
  },
  SET_MENU:(state, data)=>{
    state.menu = data
  },
 


}

const actions = {
  // user login
  login({ commit ,dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise(async (resolve, reject) => {
      login({ username: username.trim(), password: password }).then( async(response) => {
        const { data } = response
        console.log("获取得到token", data.token);
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        localStorage.setItem('userinfo', JSON.stringify( data.userinfo))
        dispatch('getInfo').then( res =>{
          console.log(  "返回的路由信息权限" ,res);
        })
          // let  info   = await _getInfo()
          // console.log(info);
          // info.data

        commit('SET_NAME', data.role)
        commit('SET_roles', data.role)
        //  除了获得了token 以外, 还需要 去添加一下 路由 信息

        
        // commit('SET_routes' ,arr )   //  防止下次刷新的时候没有路由  我们就可以在 拦截器中通过获取这个vuexroutes 来添加
      
        //  dispatch('setRouter')


        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise( async (resolve, reject) => {
     let result    = await   _getInfo()
      console.log('result_getInfo',result);

      var roles = result.data.roles.map( v =>  v.name )
   
      commit('SET_roles',roles)
      commit('SET_NAME', result.data.roles.map( v =>  v.label))
      // result.data.permissionList  转化为正常的路由
      let  routes =  render(result.data.permissionList)
   
      routes  =   creatrouter(routes , asyncRoutes)
  
      commit('SET_MENU',constantRoutes.concat(routes))
      routes.forEach(v => {
     
        console.log("添加的路由" , v);

        router.addRoute(v)
      });
      router.addRoute(asyncRoutes[asyncRoutes.length-1])
  
      resolve(result.data.permissionList)

    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })

  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

//  async setRouter({ state , commit,  dispatch}){
    
//   // setRouter
//     let {   roles ,routes   } =  await dispatch('getRoutes')
//     console.log("得到的路由");

//     commit('SET_roles',roles)
//   var arr = [...constantRoutes]
//     creatrouter(routes, asyncRoutes).forEach(  v =>{
//       // console.log("正在添加",v);
//       arr.push(v)
//       router.addRoute(v)
//     } )
//     router.addRoute(asyncRoutes[asyncRoutes.length-1])
// //  渲染菜单

//       commit('SET_MENU',arr)

//   }
//   ,

  getRoutes(){
      return  { 
        roles:['admin'],
        routes :[
        {  
          menuName:"订单",
          permissionList:[
             {  menuName :"结算中心" },
             {  menuName :"订单" }
          ]
       },
       {   menuName:"小说",
       permissionList:[
          {  menuName :"小说列表" },
          {  menuName :"添加小说" },
       ]
   
       },
       {   menuName:"代理",
       permissionList:[
          {  menuName :"添加代理" },
          {  menuName :"代理" },
       ]
   
       },
       {   menuName:"客户信息",
       permissionList:[
          {  menuName :"用户" },
          {  menuName :"账单地址" },
       ]
   
       }
      ]}

  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

